package pro.bbs.server.datasource;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * <p>
 * 初始化数据源论坛数据源
 * </p>
 *
 * @author 杨阳
 * @since 2017年10月16日
 */
@Configuration
@MapperScan(basePackages = {"pro.bbs.server.mapper.bbs"}, sqlSessionFactoryRef = "bbsSqlSessionTemplate")
public class BbsDataSourceConfig {
    @Value("${bbs.url}")
    private String bbsUrl;
    @Value("${username}")
    private String username;
    @Value("${password}")
    private String password;
    @Value("${driver-class-name}")
    private String driverClassName;
    @Value("${validation-query}")
    private String validationQuery;

    /**
     * <p>
     * 配置论坛数据源
     * </p>
     *
     * @return {@link DataSource}
     */
    @Bean(name = "bbsDS")
    @Primary
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(bbsUrl);
        dataSource.setDriverClassName(driverClassName);
        dataSource.setValidationQuery(validationQuery);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }


    @Bean(name = "bbsSqlSessionTemplate")
    @Primary
    public SqlSessionFactory bbsSqlSessionTemplate(@Qualifier("bbsDS") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/bbs/*.xml"));
        return bean.getObject();
    }

    @Bean(name = "bbsTransactionManager")
    @Primary
    public DataSourceTransactionManager bbsTransactionManager(@Qualifier("bbsDS") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

}
